package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request  response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.通过request 对象获取请求地址
        String path = request.getURI().getPath();
        //3.判断请求地址是否是登录，如果是则放行
        if (path.contains("/login_auth")){
            return chain.filter(exchange);
        }

        //4.如果不是，则获取请求头里面的token
        String token = request.getHeaders().getFirst("token");
        //5.判断token是否为空，如果为空则返回401
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.如果不为空则校验token的合法性和有效性，如果校验通过则放行，如果不通过则返回401
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token); //为什么要try catch 因为如果传过来的token是过期的，这一段代码会抛异常

            int result = AppJwtUtil.verifyToken(claimsBody);
            if (1 == result || 2 == result ){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //通过token获取用户id
            String id = claimsBody.get("id").toString();
            //对request请求头进行增强,添加一个Key-Value键值对
            ServerHttpRequest serverHttpRequest = request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId", id);
                }
            }).build();

            //替换老的request对象
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return chain.filter(exchange);
    }

    /**
     * 返回值是用来做过滤器排序的，值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
